#include <stdio.h>

#include "DataElement.h"
#include "DoubkyLinkList.h"


/**
 *
 * @param dList
 * @param position
 * @param element
 */
void InsertDoublyLinkList(DoublyLinkList *dList, int position, ElementType element) {
    /* 创建空节点 */
    DoublyNode *node = (DoublyNode *) malloc(sizeof(DoublyNode));
    node->data = element;
    node->prior = NULL;
    node->next = NULL;
    /* 在第一个位置插入节点 */
    if (position == 1) {
        node->next = dList->next;
        dList->next = node;
        node->next->prior = node;
        dList->length++;
        return;
    }

    DoublyNode *currNode = dList->next;
    for (int i = 0; currNode && i < position - 1; i++) {
        node->prior = currNode;
        /* 如果前缀节点非空,因为空就表示没有后继节点了 */
        if (currNode->next) {
            /* 将插入位置处的前缀节点指向新节点 */
            currNode->next->prior = node;
        }
        node->next = currNode->next;
        currNode->next = node;
        dList->length++;
    }

}

/**
 *
 * @param dList
 */
void PrintDoublyLinkList(DoublyLinkList *dList) {
    DoublyNode *node = dList->next;
    if (!node || dList->length == 0) {
        printf("链表为空,没有什么内容可以打印!\n");
        dList->length = 0;
        return;
    }

    for (int i = 0; i < dList->length; i++) {
        printf("%d\t%s", node->data.id, node->data.name);
    }
}
